package com.ald.crossex.service;

import com.ald.crossex.dao.CeCoreResourceDao;
import com.ald.crossex.dao.VResourceDao;
import com.ald.crossex.dto.JqGridRequest;
import com.ald.crossex.dto.ResourceDto;
import com.ald.crossex.dto.SendOrderDto;
import com.ald.crossex.entity.TCeCoreResource;
import com.ald.crossex.entity.VResource;
import com.ald.crossex.entity.VSendOrder;
import com.ald.crossex.util.JqGridFilterUtils;
import com.ald.crossex.util.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lishijiong on 15/1/23.
 */
@Service
public class ResourceService {

    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Autowired
    private CeCoreResourceDao resourceDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private VResourceDao vResourceDao;

    /**
     * 新增资源
     * @param res
     */
    public void addResource(TCeCoreResource res){

        TCeCoreResource parent = resourceDao.query(res.getParentId());
        res.setLevel(parent.getLevel()+1);
        res.setSort(res.getSort()==null?getResourceMaxSortByParentId(res.getParentId())+1:res.getSort());

        resourceDao.create(res);

    }

    /**
     * 更新资源
     * @param resource
     */
    public void updateResource(TCeCoreResource resource){
        TCeCoreResource res  = resourceDao.query(resource.getRid());

        TCeCoreResource parent = resourceDao.query(resource.getParentId());
        res.setName(resource.getName());
        res.setSort(res.getSort()==null?getResourceMaxSortByParentId(res.getParentId())+1:res.getSort());
        res.setIconClass(resource.getIconClass());
        res.setUrl(resource.getUrl());
        res.setType(resource.getType());
        res.setLevel(parent.getLevel()+1);
        res.setParentId(parent.getRid());
        res.setRemark(resource.getRemark());

        resourceDao.update(res);
    }

    /**
     * 获取当前节点下最大的排序号
     * @param parentId
     * @return
     */
    public int getResourceMaxSortByParentId(Integer parentId){
        int result = jdbcTemplate.queryForInt("select max(sort) from ce_core_resource where parent_id = " + parentId);
        return result;
    }

    /**
     * 删除资源
     * @param rIds
     * @return
     */
    public int delResource(String rIds){
        int i=0;
        String[] ids = rIds.split(",");
        for(;i<ids.length;i++){
            hibernateTemplate.bulkUpdate("delete from TCeCoreResource where rid = ?",new Object[]{Integer.parseInt(ids[i])});
        }
        return i;
    }

    /**
     * 资源列表
     * @param request
     * @return
     */
    public Page listFirstLevelResource(JqGridRequest request){
        Page page = new Page(request.getPage(), request.getRows());
        String conditionSql = " where 1=1 ";
        if (StringUtils.isNotEmpty(request.getFilters())) {
            conditionSql += JqGridFilterUtils.convertJqGridFilter2String(request.getoFilters());
        }

        String orderSql = " order by level, parentId," + (StringUtils.isEmpty(request.getSidx()) ? " sort" : request.getSidx()) + " " + request.getSord();

        List<VResource> list = vResourceDao.queryPageByHQL("select  count(*) from VResource o " + conditionSql, "from VResource o " + conditionSql + orderSql, new Object[]{}, page);

        page.setDatas(list);
        return page;

    }

    /**
     * 根据父id查询资源列表
     * @param request
     * @return
     */
    public Page listResourceByParentId(JqGridRequest request){
        Page page = new Page(request.getPage()==null?1:request.getPage(), request.getRows()==null?20:request.getRows());
        request.setNodeid(request.getNodeid() == null ? "1" : request.getNodeid());
        String conditionSql = " where 1=1 and parent_id = ?";
        List<TCeCoreResource> list = vResourceDao.queryPageByHQL("select  count(*) from TCeCoreResource o " + conditionSql, "select ce.`name`,ce.`level`,ce.sort,ce.type,ce.url ,ce.parent_id,ce.icon_class,ce.remark,ce.rid,\n" +
                "case when (select count(*) from ce_core_resource re where re.parent_id = ce.rid) <= 0 then  true else false end as isLeaf,\n" +
                "case ce.parent_id when 1 then '#' else (select rep.`name` from ce_core_resource rep where rep.rid = ce.parent_id) end as parent\n" +
                "from ce_core_resource ce " + conditionSql, new Object[]{Integer.parseInt(request.getNodeid())}, page);
        List<ResourceDto> dtos = new ArrayList<ResourceDto>();
        for (TCeCoreResource o : list) {
            ResourceDto dto = new ResourceDto();
            BeanUtils.copyProperties(o, dto);
            dtos.add(dto);
        }

        page.setDatas(dtos);
        return page;
    }

    /**
     * 获取资源树型结构
     * @return
     */
    public List<ResourceDto> getResourceTree(){
        return getResourceTreeByParent(1);
    }
    /**
     * 根据资源id获取树型结构
     * @return
     */
    public List<ResourceDto> getResourceTreeByParent(Integer parentId){
        List<TCeCoreResource> list = resourceDao.queryByHql("from TCeCoreResource o where parentId = ? ",new Object[]{parentId});
        List<ResourceDto> resDtos = new ArrayList<ResourceDto>();
        for(TCeCoreResource t :list){
            ResourceDto dto = new ResourceDto();
            BeanUtils.copyProperties(t, dto);
            dto.setChildren(getResourceTreeByParent(t.getRid()));
            resDtos.add(dto);
        }
        return resDtos;
    }



    public List<ResourceDto> getResourceByUser(Integer userId) {

        if (userId != null) {
            return getResourceByUserAndParent(userId, 1);
        } else {
            return null;
        }
    }

    /**
     * 获取有权限的资源
     *
     * @param userId
     * @param parentId
     * @return
     */
    private List<ResourceDto> getResourceByUserAndParent(Integer userId, Integer parentId) {
        List<Map<String, Object>> items = jdbcTemplate.queryForList(" select res.rid,res.name,res.type,res.url,res.level,res.parent_id,res.sort,res.icon_class from ce_core_resource res  \n" +
                " join ce_core_role_resource rlrs on res.rid = rlrs.resource_id\n" +
                " join ce_core_user_role usrl on usrl.role_id = rlrs.role_id  \n" +
                " where usrl.user_id = ? \n" +
                " and res.parent_id = ? \n" +
                " and res.type = 'url' " +
                " order by res.sort asc ", new Object[]{userId, parentId});

        List<ResourceDto> resDtos = new ArrayList<ResourceDto>();

        for (Map<String, Object> item : items) {
            ResourceDto dto = new ResourceDto();
            dto.setRid((Integer) item.get("rid"));
            dto.setName((String) item.get("name"));
            dto.setType((String) item.get("type"));
            dto.setUrl((String) item.get("url"));
            dto.setLevel((Integer) item.get("level"));
            dto.setSort((Integer) item.get("sort"));
            dto.setParentId((Integer) item.get("parent_id"));
            dto.setIconClass((String) item.get("icon_class"));
            dto.setChildren(getResourceByUserAndParent(userId, dto.getRid()));
            resDtos.add(dto);
        }

        return resDtos;
    }

}
